package com.nowcoder.community.event;

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.entity.Message;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.ElasticsearchService;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.util.CommunityConstant;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class EventConsumer implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(EventConsumer.class);

    @Autowired
    private MessageService messageService;//处理事件最终是给用户发消息(往消息表中插入数据)

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private ElasticsearchService elasticsearchService;

    @KafkaListener(topics = {TOPIC_COMMENT, TOPIC_LIKE, TOPIC_FOLLOW})
    public void handleCommentMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            logger.error("消息的内容为空!");
            return;
        }

        //消费者要将原始的数据(Event对象)转换为消息数据(Message对象)
        // Message对象中包含基础数据和内容(为了呈现给页面所需要的数据)

        //获取事件对象(事件触发时封装了相关的数据)
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);//将字符串转为对象
        if (event == null) {//对象为空
            logger.error("消息格式错误!");
            return;
        }

        // 发送站内通知(对message表格的复用(会话id(主题类型)和内容(对象))
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);//消息的发布者
        message.setToId(event.getEntityUserId());//消息的接收者
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());

        //封装呈现给页面的数据
        Map<String, Object> content = new HashMap<>();
        content.put("userId", event.getUserId());//事件的触发者
        content.put("entityType", event.getEntityType());//实体类型
        content.put("entityId", event.getEntityId());//具体实体的id

        if (!event.getData().isEmpty()) {
            for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                content.put(entry.getKey(), entry.getValue());
            }
        }

        message.setContent(JSONObject.toJSONString(content));
        messageService.addMessage(message);//往消息表中插入数据
    }

    // 消费发帖事件
    @KafkaListener(topics =  {TOPIC_PUBLISH})
    public void handlePublishMessage(ConsumerRecord record){
        if (record == null || record.value() == null) {
            logger.error("消息的内容为空!");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);//将字符串转为对象
        if (event == null) {//对象为空
            logger.error("消息格式错误!");
            return;
        }

        DiscussPost post = discussPostService.findDiscussPostById(event.getEntityId());
        elasticsearchService.saveDiscussPost(post);
    }
}
